package com.management.department.teacherinfosystem.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import java.nio.charset.StandardCharsets;

@Component
public class CourseHoursDatabaseInitializer implements CommandLineRunner {
    
    private static final Logger logger = LoggerFactory.getLogger(CourseHoursDatabaseInitializer.class);
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Override
    public void run(String... args) throws Exception {
        logger.info("开始初始化教学课时模块数据库表...");
        
        try {
            // 读取并执行schema.sql
            ClassPathResource schemaResource = new ClassPathResource("db/course_hours_schema.sql");
            if (schemaResource.exists()) {
                logger.info("找到course_hours_schema.sql文件，开始执行...");
                String schemaSql = StreamUtils.copyToString(schemaResource.getInputStream(), StandardCharsets.UTF_8);
            
                                    // 分割SQL语句并执行
                        String[] sqlStatements = schemaSql.split(";");
                        for (String sql : sqlStatements) {
                            sql = sql.trim();
                            if (!sql.isEmpty()) {
                                try {
                                    jdbcTemplate.execute(sql);
                                    logger.info("执行SQL成功: {}", sql.substring(0, Math.min(sql.length(), 50)) + "...");
                                } catch (Exception e) {
                                    logger.warn("执行SQL失败，可能表已存在: {}", e.getMessage());
                                }
                            }
                        }
                        
                        // 设置数据库连接字符编码
                        jdbcTemplate.execute("SET NAMES utf8mb4");
                        jdbcTemplate.execute("SET CHARACTER SET utf8mb4");
                        jdbcTemplate.execute("SET character_set_connection=utf8mb4");
                    } else {
                        logger.warn("course_hours_schema.sql文件不存在，跳过表结构创建");
                    }
            
            // 读取并执行data.sql
            ClassPathResource dataResource = new ClassPathResource("db/course_hours_data.sql");
            String dataSql = StreamUtils.copyToString(dataResource.getInputStream(), StandardCharsets.UTF_8);
            
            // 分割SQL语句并执行
            String[] dataStatements = dataSql.split(";");
            for (String sql : dataStatements) {
                sql = sql.trim();
                if (!sql.isEmpty()) {
                    try {
                        jdbcTemplate.execute(sql);
                        logger.info("执行数据插入SQL成功: {}", sql.substring(0, Math.min(sql.length(), 50)) + "...");
                    } catch (Exception e) {
                        logger.warn("执行数据插入SQL失败: {}", e.getMessage());
                    }
                }
            }
            
            logger.info("教学课时模块数据库表初始化完成！");
            
        } catch (Exception e) {
            logger.error("初始化教学课时模块数据库表失败: {}", e.getMessage(), e);
        }
    }
}
